import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import { verifySession } from './utils/auth.js';
import * as authRoutes from './routes/auth.js';
import * as chapterRoutes from './routes/chapters.js';
import * as modelRoutes from './routes/models.js';
import * as modelStateRoutes from './routes/modelStates.js';
import settingsRouter from './routes/settings.js';

const app = express();
const PORT = 3004;
const BASE_PATH = '/geometry';

// 中间件
app.use(cors());
app.use(bodyParser.json());

// 身份验证中间件
const requireAuth = (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');
  
  if (!token || !verifySession(token)) {
    return res.status(401).json({ error: '未授权，请先登录' });
  }
  
  next();
};

// ============ 认证 API ============
app.get(`${BASE_PATH}/api/auth/captcha`, authRoutes.getCaptcha);
app.post(`${BASE_PATH}/api/auth/login`, authRoutes.login);
app.post(`${BASE_PATH}/api/auth/logout`, authRoutes.logout);
app.get(`${BASE_PATH}/api/auth/verify`, authRoutes.verify);
app.put(`${BASE_PATH}/api/auth/password`, requireAuth, authRoutes.changePasswordRoute);

// ============ 章节 API ============
app.get(`${BASE_PATH}/api/chapters`, chapterRoutes.getAllChapters);
app.get(`${BASE_PATH}/api/chapters/:id`, chapterRoutes.getChapterById);
app.post(`${BASE_PATH}/api/chapters`, requireAuth, chapterRoutes.createChapter);
app.put(`${BASE_PATH}/api/chapters/:id`, requireAuth, chapterRoutes.updateChapter);
app.delete(`${BASE_PATH}/api/chapters/:id`, requireAuth, chapterRoutes.deleteChapter);

// ============ 几何模型 API ============
app.get(`${BASE_PATH}/api/models`, modelRoutes.getAllModels);
app.get(`${BASE_PATH}/api/models/:id`, modelRoutes.getModelById);
app.post(`${BASE_PATH}/api/models`, requireAuth, modelRoutes.createModel);
app.put(`${BASE_PATH}/api/models/:id`, requireAuth, modelRoutes.updateModel);
app.delete(`${BASE_PATH}/api/models/:id`, requireAuth, modelRoutes.deleteModel);
// 特殊模型专用接口
app.delete(`${BASE_PATH}/api/models/:id/special`, requireAuth, modelRoutes.deleteSpecialModel);
app.put(`${BASE_PATH}/api/models/:id/template`, requireAuth, modelRoutes.updateSpecialModelTemplate);
app.put(`${BASE_PATH}/api/models/:id/hidden`, requireAuth, modelRoutes.updateSpecialModelHidden);

// ============ 模型状态 API ============
app.get(`${BASE_PATH}/api/models/:modelId/states`, modelStateRoutes.getModelStates);
app.post(`${BASE_PATH}/api/models/:modelId/states`, requireAuth, modelStateRoutes.createState);
app.put(`${BASE_PATH}/api/states/:id`, requireAuth, modelStateRoutes.updateState);
app.delete(`${BASE_PATH}/api/states/:id`, requireAuth, modelStateRoutes.deleteState);
app.post(`${BASE_PATH}/api/models/:modelId/states/reorder`, requireAuth, modelStateRoutes.reorderStates);

// ============ 设置 API ============
app.use(`${BASE_PATH}/api/settings`, settingsRouter);

// 健康检查
app.get(`${BASE_PATH}/api/health`, (req, res) => {
  res.json({ status: 'ok', message: '几何模型管理系统运行中' });
});

app.listen(PORT, () => {
  console.log(`🚀 服务器运行在 http://localhost:${PORT}${BASE_PATH}`);
  console.log(`📚 API文档:`);
  console.log(`   章节: GET/POST/PUT/DELETE ${BASE_PATH}/api/chapters`);
  console.log(`   模型: GET/POST/PUT/DELETE ${BASE_PATH}/api/models`);
  console.log(`   认证: GET/POST ${BASE_PATH}/api/auth/*`);
});

